import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';
import store from '@/store';

const vm = new Vue({});
const baseURL = process.env.NODE_ENV === 'development' ?
  'http://ydnxapi.kjgoods.com/' :
  'http://ydnxapi.kjgoods.com/';
const request = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
  crossDomain: true,
  // timeout: 20000
});

// 发送前拦截并修改 config
request.interceptors.request.use(config => {
  store.state.isLoading = true;
  return config;
}, error => {
  return Promise.reject(error);
});


// 响应拦截
request.interceptors.response.use(response => {
  store.state.isLoading = false;
  return response.data || {
    status: response.status >= 200 && response.status < 400,
    message: response.statusText
  };
}, error => {
  store.state.isLoading = false;
  vm.$notify.danger({ content: error.request.status + ' : ' + error.request.statusText });
  Promise.reject(error); // 把错误传递下去
});

const convertToFormData = (data) => {
  const formData = new FormData();
  for (let key in data) {
    formData.append(key, data[key]);
  }
  return formData;
};

export { request, baseURL, convertToFormData };
